/**
/**
 * JAVACC DEMO 1.0
 */

package freemarker.core;

import java.io.IOException;
import java.util.List;

import freemarker.cache.TemplateCache;
import freemarker.core.Environment;
import freemarker.template.Template;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;

/**
 * description:  
 * @author Hou Dayu 创建时间：2016-7-28
 */
public class ExistMethodModel implements TemplateMethodModel {

	public static final String METHOD_NAME = "exist";

	public Object exec(List arguments) throws TemplateModelException {
		if (arguments.size() != 1) {
			throw new TemplateModelException("Wrong arguments");
		}
		String name = (String) arguments.get(0);
		return Boolean.valueOf(isExist(name, null, true));
	}

	public boolean isExist(String name, String encoding, boolean parse) {
		try {
			Environment env = Environment.getCurrentEnvironment();
			String includeTemplateName = TemplateCache.getFullTemplatePath(env, getTemplatePath(env), name);
			Template template = env.getTemplateForInclusion(includeTemplateName, encoding, parse);
			return template != null;
		} catch (IOException e) {
		}
		return false;
	}

	public String getTemplatePath(Environment env) {
		String templateName = env.getTemplate().getName();
		int lastSlash = templateName.lastIndexOf(47);
		return lastSlash == -1 ? "" : templateName.substring(0, lastSlash + 1);
	}

}
